package br.edu.ufcg.greengrid.event.reader;

import br.edu.ufcg.greengrid.event.Event;
import br.edu.ufcg.greengrid.event.JobSubmissionEvent;

public class JobSubmissionEventReader extends EventReader<JobSubmissionEvent> {

	private long clockStartTime;

	private Long delta;

	private Long normalizedDelta;

	public JobSubmissionEventReader() {

		this(0L, null);
	}

	public JobSubmissionEventReader(long clockStartTime, Long delta) {

		this.clockStartTime = clockStartTime;
		this.delta = delta;
		if (this.delta == null) {
			this.normalizedDelta = 0L;
		}
	}

	protected boolean run(JobSubmissionEvent event) {

		return event.getRuntime() > 0;
	}

	@Override
	protected JobSubmissionEvent getEvent(String line) {

		String[] split = line.split(Event.SEPARATOR);
		int index = 0;
		String id = split[index++];
		long submittime = Long.parseLong(split[index++]);
		JobSubmissionEvent event = new JobSubmissionEvent(id , submittime + getNormalizedDelta(submittime), Long
				.parseLong(split[index++]));
		return event;
	}

	private long getNormalizedDelta(long submittime) {

		if (this.normalizedDelta == null) {
			this.normalizedDelta = getNormalizedDelta(this.clockStartTime, this.delta, submittime);
		}
		return this.normalizedDelta;
	}

	protected long getNormalizedDelta(long clockStartTime, Long delta, long firstSubmittime) {

		if (delta == null) {
			return 0L;
		}

		return clockStartTime - firstSubmittime + delta;
	}

}
